﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;

namespace CoolCode.Data.Xml
{
    class ExpressionBuilder
    {
        public Expression<Func<XElement, bool>> Where(string[] props, string[] args)
        {
            // instance  
            ParameterExpression s = Expression.Parameter(typeof(XElement), "s");
            // method                           
            var m = typeof(XElement).GetMethod("Element", new Type[] { typeof(XName) });
            Expression cond = Expression.Constant(true);
            for (int i = 0; i < props.Length; i++)
            {
                var mcall = Expression.Call(s, m,
                        new Expression[] { Expression.Constant((XName)props[i], typeof(XName)) }             // arguments  
                       );
                var prop = Expression.Property(mcall, "Value");
                var value = Expression.Constant(args[i], typeof(string));
                cond = BinaryExpression.And(cond, BinaryExpression.Equal(prop, value));
            }
            // lambda
            var lambda = Expression.Lambda<Func<XElement, bool>>(cond, new ParameterExpression[] { s });
            return lambda;
        }

    }
}
